# /lab_booking/utils/wechat_auth.py

import requests
from fastapi import HTTPException
from lab_booking.config import settings

def get_openid_from_wechat(code: str) -> str:
    """
    使用前端提供的 code 向微信服务器换取 openid。
    """
    url = (
        f"https://api.weixin.qq.com/sns/jscode2session"
        f"?appid={settings.WECHAT_APPID}"
        f"&secret={settings.WECHAT_APPSECRET}"
        f"&js_code={code}"
        f"&grant_type=authorization_code"
    )
    
    try:
        response = requests.get(url, timeout=5) # 设置5秒超时
        response.raise_for_status() # 如果请求失败 (非2xx状态码)，则抛出异常
        data = response.json()
    except requests.exceptions.RequestException as e:
        raise HTTPException(status_code=503, detail=f"Failed to connect to WeChat API: {e}")

    if "errcode" in data and data["errcode"] != 0:
        raise HTTPException(status_code=400, detail=f"WeChat API Error: [{data['errcode']}] {data['errmsg']}")
    
    openid = data.get("openid")
    if not openid:
        raise HTTPException(status_code=500, detail="Failed to get openid from WeChat response")
        
    return openid